//
//  SearchViewController.m
//  DWL_Vogue
//
//  Created by diaowenli on 15/11/5.
//  Copyright (c) 2015年 Forlosan. All rights reserved.
//

#import "SearchViewController.h"
#import "WidthAndHeight.h"
#import "VogueHeader.h"
#import "SearchInformation.h"
#import "SearchTableViewCell.h"
#import "SearchWebViewController.h"

@interface SearchViewController()<UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource>
@property(nonatomic, retain)UISearchBar *searchBar;
@property(nonatomic, retain)UITableView *searchTableView;
@property(nonatomic, retain)NSMutableArray *searchArr;
@property(nonatomic, assign)NSInteger num;

@end

@implementation SearchViewController
- (void)dealloc {
    [_searchBar release];
    [_searchTableView release];
    [_searchTableView release];
    
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
    [self.view addSubview:headView];
    headView.backgroundColor = [UIColor colorWithRed:54 / 255.0 green:53 / 255.0 blue:68 / 255.0 alpha:1];
    [headView release];
    
    UIButton *headButton = [UIButton buttonWithType:UIButtonTypeSystem];
    headButton.frame = CGRectMake(16, 25, 32, 32);
    [headButton setImage:[UIImage imageNamed:@"return.png"] forState:UIControlStateNormal];
    [headButton setTintColor:[UIColor whiteColor]];
    [headView addSubview:headButton];
    [headButton addTarget:self action:@selector(leftButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(60, 25, WIDTH - 120, 30)];
    self.searchBar.layer.borderWidth = 8;
    self.searchBar.layer.borderColor = [UIColor whiteColor].CGColor;
    self.searchBar.layer.cornerRadius = 5;
    self.searchBar.layer.masksToBounds = YES;
    [headView addSubview:self.searchBar];
    self.searchBar.placeholder = @"搜索";
    [self.searchBar setTintColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar bringSubviewToFront:self.searchBar];
    [self.searchBar setTranslucent:YES];
    self.searchBar.delegate = self;
    [_searchBar release];
    
    //    TableView
    self.searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.searchTableView];
    [_searchTableView release];
    self.searchTableView.delegate = self;
    self.searchTableView.dataSource = self;
    self.searchTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footer)];
    self.num = 0;
}

- (void)footer {
    self.num = self.num + 10;
    
    NSString *urlStr = @"http://www.ecook.cn/public/searchRecipe.shtml";
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *str = [self.searchBar.text  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *url1 = [NSString stringWithFormat:@"machine=O0fd7f8732e846e4d9576337a9bd7acf37c68306d&vession=11.0.4.1&begin=%ld", self.num];
    NSString *url2 = [url1 stringByAppendingString:@"&queryString="];
    NSString *bodyStr = [url2 stringByAppendingString:str];
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];
    
    //  建立连接
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    for (NSMutableDictionary *dic1 in dic[@"contentList"]) {
        SearchInformation *search = [[SearchInformation alloc] init];
        [search setValuesForKeysWithDictionary:dic1];
        [self.searchArr addObject:search];
        [search release];
    }
    [self.searchTableView.footer endRefreshing];
    [self.searchTableView reloadData];
}

- (void)createData {
    //    AFHTTPRequestOperationManager *managerScroll = [AFHTTPRequestOperationManager manager];
    //    managerScroll.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/json", @"text/javascript", @"text/html", @"application/json", nil];
    //    [managerScroll POST:@"http://www.ecook.cn/public/searchRecipe.shtml " parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    //        NSLog(@"%@", responseObject);
    //    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    //        NSLog(@"%@", error);
    //    }];
    
    NSString *urlStr = @"http://www.ecook.cn/public/searchRecipe.shtml";
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *str = [self.searchBar.text  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *bodyStr = [NSString stringWithFormat:@"machine=O0fd7f8732e846e4d9576337a9bd7acf37c68306d&vession=11.0.4.1&begin=0&queryString=%@", str];
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];
    
    //  建立连接
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    
    self.searchArr = [NSMutableArray array];
    for (NSMutableDictionary *dic1 in dic[@"contentList"]) {
        SearchInformation *search = [[SearchInformation alloc] init];
        [search setValuesForKeysWithDictionary:dic1];
        [self.searchArr addObject:search];
        [search release];
    }
    [self.searchTableView reloadData];
}

#pragma searchBar
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [searchBar resignFirstResponder];
        [self.view bringSubviewToFront:self.searchTableView];
    [self createData];
}

- (void)leftButtonClick {
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma mark  TableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.searchArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse1 = @"reuse1";
    SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse1];
    if (!cell) {
        cell = [[[SearchTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse1]autorelease];
    }
    SearchInformation *search = self.searchArr[indexPath.row];
    [cell.searchImageView sd_setImageWithURL:[NSURL URLWithString:[[@"http://pic.ecook.cn/web/" stringByAppendingString:search.imageid] stringByAppendingString:@".jpg!m3"]] placeholderImage:[UIImage imageNamed:@"placeholderSmall.jpg"]];
    cell.searchTitleLabel.text = [[search.searchName stringByReplacingOccurrencesOfString:@"/ecook" withString:@""] stringByReplacingOccurrencesOfString:@"ecook" withString:@""];
    cell.searchContentLabel.text = search.content;
    
    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:cell.searchTitleLabel.text];
    [attribute addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[cell.searchTitleLabel.text rangeOfString:self.searchBar.text]];
    [cell.searchTitleLabel setAttributedText:attribute];
    [attribute release];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    SearchWebViewController *web = [[SearchWebViewController alloc] init];
    web.url = [self.searchArr[indexPath.row] searchUrl];
    [self presentViewController:web animated:YES completion:nil];
    [web release];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return WIDTH / 4;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end